Imports System
Imports CObject
Imports ConnectionServer
Imports System.Data.SqlClient
Imports System.IO
Imports System.Reflection
Imports System.Text.RegularExpressions
Imports System.Web
Imports System.Net.Mail
Imports Objects.Security.Cryptography


Namespace Utility
    Public Class UtilityFunctions

        Private _msReportingEmail As String = String.Empty

        Public Sub New()

            Dim loSetting As Settings = New Settings(Connection.SourceDataBase.CMT)
            _msReportingEmail = loSetting("ReportingEmail").ToString

        End Sub

        Public ReadOnly Property ReportingEmailAddress() As String
            Get
                Return _msReportingEmail
            End Get
        End Property

        Public Function CleanFileName(ByVal psStr As String) As String

            psStr = psStr.Replace("'", "")
            psStr = psStr.Replace("#", "")
            psStr = psStr.Replace("$", "")
            psStr = psStr.Replace("%", "")
            psStr = psStr.Replace(",", "")
            psStr = psStr.Replace("`", "")
            psStr = psStr.Replace("~", "")
            psStr = psStr.Replace("!", "")
            psStr = psStr.Replace("@", "")
            psStr = psStr.Replace("^", "")
            psStr = psStr.Replace("&", "")
            psStr = psStr.Replace("(", "")
            psStr = psStr.Replace(")", "")
            psStr = psStr.Replace("-", "")
            psStr = psStr.Replace("+", "")
            psStr = psStr.Replace("=", "")
            psStr = psStr.Replace("[", "")
            psStr = psStr.Replace("]", "")
            psStr = psStr.Replace("{", "")
            psStr = psStr.Replace("}", "")
            psStr = psStr.Replace(";", "")
            If psStr.LastIndexOf(".") > 0 Then
                Dim liIndex As Integer = Len(psStr) - psStr.LastIndexOf(".") - 1
                psStr = psStr.Replace(".", "")
                Dim liNewIndex As Integer = Len(psStr) - liIndex
                psStr = psStr.Insert(liNewIndex, ".")
            End If
            Return psStr

        End Function

        Private Function GetSMTPServer() As String
            Dim loSettings As New Settings(Connection.SourceDataBase.CMT)
            
                Return loSettings("smtpserver")


        End Function
        Private Function GetEmailTag() As String
            Dim loSettings As New Settings(Connection.SourceDataBase.CMT)
            Dim lsTag As String = "<p>***Please do not reply to this email. </p>"
            If loSettings("emailtag") Is Nothing OrElse loSettings("emailtag").Length = 0 Then
                Return lsTag
            Else
                Return loSettings("emailtag")
            End If
        End Function

   
        Public Function InstantiateTypeByName(ByVal psTypeName As String) As CObject.CObject
            If Not psTypeName Is Nothing AndAlso psTypeName.Trim.Length > 0 Then
                Dim loAss As [Assembly] = Reflection.Assembly.Load("Objects")
                Return CType(loAss.CreateInstance(psTypeName), CObject.CObject)
            Else
                Return Nothing
            End If

        End Function
        Public Function UploadDocument(ByVal psTargetPath As String, ByVal HTMLFileUploadObject As Web.UI.HtmlControls.HtmlInputFile) As String
            Dim lsfileName As String

            Dim lsSavePath As String
            Dim loFileInfo As FileInfo
            Dim loDirInfo As DirectoryInfo = New DirectoryInfo(psTargetPath)
            If Not loDirInfo.Exists Then
                loDirInfo.Create()
            End If
            lsfileName = System.IO.Path.GetFileName(HTMLFileUploadObject.PostedFile.FileName)
            lsSavePath = loDirInfo.FullName & "/" & lsfileName
            loFileInfo = New FileInfo(lsSavePath)
            If loFileInfo.Exists Then
                loFileInfo.Delete()
            End If

            If lsfileName.Length > 0 Then
                HTMLFileUploadObject.PostedFile.SaveAs(lsSavePath)
            End If
            Return loFileInfo.FullName
        End Function
        'Depreciated
        Public Sub UploadFile(ByVal HTMLFileUploadObject As System.Web.UI.HtmlControls.HtmlInputFile, ByVal pstrTargetPath As String)
            Dim lstrSavePath As String
            Dim lobjDirInfo As DirectoryInfo = New DirectoryInfo(pstrTargetPath)
            If Not lobjDirInfo.Exists Then
                lobjDirInfo.Create()
            End If
            lstrSavePath = lobjDirInfo.FullName
            If System.IO.Path.GetFileName(HTMLFileUploadObject.PostedFile.FileName).Length > 0 Then
                HTMLFileUploadObject.PostedFile.SaveAs(lstrSavePath)
            End If
        End Sub
        Public Sub ResizeImage(ByVal pstrFileName As String, ByVal pshtWidth As Short)
            Dim limgFile As System.Drawing.Image = Nothing
            Dim limgNewFile As System.Drawing.Image = Nothing
            Dim lbooSuccess As Boolean = False
            While Not lbooSuccess
                Try
                    limgFile = Drawing.Image.FromFile(pstrFileName)
                    lbooSuccess = True
                Catch ex As Exception
                    lbooSuccess = False
                End Try
            End While
            If lbooSuccess AndAlso limgFile.Width > pshtWidth Then
                Dim lshtHeight As Short = CShort(limgFile.Height / (limgFile.Width / pshtWidth))
                limgNewFile = limgFile.GetThumbnailImage(pshtWidth, lshtHeight, Nothing, System.IntPtr.Zero)
                limgFile.Dispose()
                limgNewFile.Save(pstrFileName, System.Drawing.Imaging.ImageFormat.Jpeg)
            Else
                limgFile.Dispose()
            End If
        End Sub

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        '''     This subroutine logs the erros and exceptions in to a Application Log. We can view 
        '''     it by browsing through Eventviewer/Application.    
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' 	[ ]	06/09/2005	Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Public Sub LogErrorEvents(ByVal sender As Object, ByVal e As EventArgs, ByVal ex As Exception)

            Dim loException As Exception = ex.GetBaseException
            Dim Message As String = String.Empty


            Message = Message & " Error: " & loException.Message & vbCrLf & "Stack:" & loException.StackTrace

            Dim Log As EventLog = New EventLog
            If Not EventLog.SourceExists("OSCAR") Then
                EventLog.CreateEventSource("OSCAR", "Application")
            End If
            Log.Source = "OSCAR"
            EventLog.WriteEntry("OSCAR", Message, EventLogEntryType.Error)


        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        '''     This fucntion parses the given text based on the given start and end delimiters
        '''     and returns the results in the arraylist. 
        '''     EX: source is "This is a {Test} I am Testing {this}"
        '''         it returns the array list of strings Test, this        
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' 	06/15/2005	Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Public Function ParseText(ByVal strSrcText As String, ByVal strStartDelimiter As String, ByVal strEndDelimiter As String) As ArrayList

            Dim lalDest As New ArrayList
            Dim laoTemp() As String
            Dim laoTemp2() As String
            Dim liCount As Integer


            laoTemp = strSrcText.Split(CChar(strStartDelimiter))
            For liCount = laoTemp.GetLowerBound(0) To laoTemp.GetUpperBound(0)
                If laoTemp(liCount).IndexOf(strEndDelimiter) > 0 Then
                    laoTemp2 = laoTemp.GetValue(liCount).ToString.Split(CChar(strEndDelimiter))
                    If laoTemp2.Length >= 0 Then
                        lalDest.Add(laoTemp2(0).ToString.Trim())
                    End If
                End If
            Next

            Return lalDest
        End Function
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        '''     This function builds the dynamic text for EmailBody Text. If the given text has column 
        '''     names surrounded by the curly braces "{}", this columnname will be replaced with
        '''     the column value. Returns the resulting Dynamic text.
        '''     Uses: Utility.ParseText() function.
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        '''  06/15/2005	Created
        '''		8/17/2005 pdtDynamicData is not used any more.
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Public Function BuildDynamicBody(ByVal strText As String, ByVal pdtDynamicData As DataTable, ByVal pdrDynamicData As DataRow, ByVal pStdelimiter As String, ByVal pEnDelimiter As String) As String

            Dim strDynText As String
            Dim lalDynList As ArrayList = ParseText(strText, pStdelimiter, pEnDelimiter)

            Dim myEnumerator As System.Collections.IEnumerator = lalDynList.GetEnumerator()
            Dim loColumn As DataColumn
            For Each loColumn In pdrDynamicData.Table.Columns
                While myEnumerator.MoveNext()
                    If loColumn.ColumnName.Trim().ToUpper() = myEnumerator.Current().ToString.Trim().ToUpper() Then
                        strText = strText.Replace(pStdelimiter & loColumn.ColumnName.Trim().ToUpper() & pEnDelimiter, pdrDynamicData(loColumn.ColumnName).ToString)
                    End If

                End While
                ' reset the enumerator to first position
                myEnumerator.Reset()

            Next
            strDynText = strText

            Return strDynText
        End Function
    End Class
 

End Namespace